﻿Imports TBCC.UserManage
Public Class DBClearForm
    Private _pi As ProjectItem
    Private _NetIDList As New List(Of DevTypeItem)
    Private gp As System.Security.Principal.GenericPrincipal

    Private Sub DBClearForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.CenterToParent()
        _pi = MainForm.pi

        gp = My.User.CurrentPrincipal
        LoadTime()

        If LoadAllRef() = False Then
        End If
    End Sub

    Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
        If checkValidate() = False Then
            Exit Sub
        End If

        If _NetIDList.Count <= 0 Then
            msg.ShowWarning("尚未配置工程设备信息")
            Exit Sub
        End If

        If msg.ShowYesNo("确定要执行清理？（清理期间请不要关闭，过程时间依据量的不同，时间不同。请耐心等待！）") = Windows.Forms.DialogResult.Yes Then
            btnClear.Enabled = False
            Panel1.Enabled = False
            lblState.Visible = True
            Me.BackgroundWorker1.RunWorkerAsync()
        End If
    End Sub

    Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
        Me.Close()
    End Sub

    Private Function DoClear() As Integer
        Dim dts As New DevTypeService(_pi)
        DoClear = 0

        Try
            For Each dti As DevTypeItem In dts.GeDevGroupList()   '设备列表
                DoClear += DeleteData(dti.ProjectID.Replace("-", "_").Trim, dti.NetId, dtpFrom.Value, dtpTo.Value)
            Next
        Catch ex As Exception
            Me.BackgroundWorker1.CancelAsync()
            Debug.Write("DBClearForm.DoClear()")
        End Try

    End Function

    Private Function DeleteData(ByVal projectID As String, ByVal netID As Integer, ByVal startTime As DateTime, ByVal endTime As DateTime) As Integer
        DeleteData = 0

        If chkHistory.Checked Then
            '删除历史数据
            DeleteData += SqlHelper.ExecuteNonQuery(String.Format("DELETE FROM tbccHDData_{0}_{1} WHERE hDate>='{2}' AND hDate<='{3}'", _
                                                                        projectID, netID, UtilityClass.GetDateString(startTime), UtilityClass.GetDateString(endTime)), Nothing)

            '删除历史数据上传记录
            Dim sYear, sMonth, sDay, sHour, sMinute, sSecond As Integer
            Dim eYear, eMonth, eDay, eHour, eMinute, eSecond As Integer
            sYear = startTime.Year : sMonth = startTime.Month : sDay = startTime.Day
            sHour = startTime.Hour : sMinute = startTime.Minute : sSecond = startTime.Second
            eYear = endTime.Year : eMonth = endTime.Month : eDay = endTime.Day
            eHour = endTime.Hour : eMinute = endTime.Minute : eSecond = endTime.Second

            SqlHelper.ExecuteNonQuery(String.Format("DELETE FROM tbccHistoryData_{0} WHERE netID = '{1}' " & _
                                                    "AND (iYear >= '{2}' AND iMonth >= '{3}' AND iDay >= '{4}' AND iHour >= '{5}' AND iMinute >= '{6}' AND iSecond >= '{7}') " & _
                                                    "AND (iYear < '{8}'); " & _
                                                    "DELETE FROM tbccHistoryData_{0} WHERE netID = '{1}' " & _
                                                    "AND (iYear >= '{2}' AND iMonth >= '{3}' AND iDay >= '{4}' AND iHour >= '{5}' AND iMinute >= '{6}' AND iSecond >= '{7}') " & _
                                                    "AND (iYear = '{8}' AND  iMonth < '{9}'); " & _
                                                    "DELETE FROM tbccHistoryData_{0} WHERE netID = '{1}' " & _
                                                    "AND (iYear >= '{2}' AND iMonth >= '{3}' AND iDay >= '{4}' AND iHour >= '{5}' AND iMinute >= '{6}' AND iSecond >= '{7}') " & _
                                                    "AND (iYear = '{8}' AND  iMonth = '{9}' AND iDay < '{10}'); " & _
                                                    "DELETE FROM tbccHistoryData_{0} WHERE netID = '{1}' " & _
                                                    "AND (iYear >= '{2}' AND iMonth >= '{3}' AND iDay >= '{4}' AND iHour >= '{5}' AND iMinute >= '{6}' AND iSecond >= '{7}') " & _
                                                    "AND (iYear = '{8}' AND  iMonth = '{9}' AND iDay = '{10}' AND iHour < '{11}'); " & _
                                                    "DELETE FROM tbccHistoryData_{0} WHERE netID = '{1}' " & _
                                                    "AND (iYear >= '{2}' AND iMonth >= '{3}' AND iDay >= '{4}' AND iHour >= '{5}' AND iMinute >= '{6}' AND iSecond >= '{7}') " & _
                                                    "AND (iYear = '{8}' AND  iMonth = '{9}' AND iDay = '{10}' AND iHour = '{11}' AND iMinute < '{12}'); " & _
                                                    "DELETE FROM tbccHistoryData_{0} WHERE netID = '{1}' " & _
                                                    "AND (iYear >= '{2}' AND iMonth >= '{3}' AND iDay >= '{4}' AND iHour >= '{5}' AND iMinute >= '{6}' AND iSecond >= '{7}') " & _
                                                    "AND (iYear = '{8}' AND  iMonth = '{9}' AND iDay = '{10}' AND iHour = '{11}' AND iMinute = '{12}' AND iSecond <= '{13}'); ", _
                                                    projectID, netID, _
                                                    sYear, sMonth, sDay, sHour, sMinute, sSecond, _
                                                    eYear, eMonth, eDay, eHour, eMinute, eSecond _
                                        ), _
                                        Nothing _
            )
        End If

        If chkAlarm.Checked Then
            '删除历史报警文档备注
            SqlHelper.ExecuteNonQuery(String.Format("DELETE FROM tbccHDAlarmDoc WHERE projectID = '{0}' AND netID = '{1}' AND startTime>='{2}' AND startTime<='{3}'", _
                                                                                    projectID, netID, UtilityClass.GetDateString(startTime), UtilityClass.GetDateString(endTime)), Nothing)

            '删除历史报警
            DeleteData += SqlHelper.ExecuteNonQuery(String.Format("DELETE FROM tbccHDAlarmData_{0} WHERE netID = '{1}' AND startTime>='{2}' AND startTime<='{3}'", _
                                                                        projectID, netID, UtilityClass.GetDateString(startTime), UtilityClass.GetDateString(endTime)), Nothing)
        End If

    End Function

    Private Function LoadAllRef() As Boolean
        Dim isDevExist As Boolean = False

        Dim dts As New DevTypeService(_pi)
        'Dim rts As New RefTypeService(_pi)

        Me._NetIDList.Clear()

        For Each dti As DevTypeItem In dts.GeDevGroupList()   '设备列表
            isDevExist = True
            Me._NetIDList.Add(dti)
        Next

        Return isDevExist
    End Function

    Private Sub LoadTime()
        Me.dtpTo.Value = Now.ToShortDateString()
        Me.dtpFrom.Value = dtpTo.Value.AddDays(-1)
    End Sub

    ''' <summary>
    ''' 检查输入数据的合法性
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function checkValidate() As Boolean
        Dim tip As String

        '检查时间范围
        If Me.dtpTo.Value <= Me.dtpFrom.Value Then
            tip = "终止时间 必须大于 起始时间。"
            msg.ShowWarning(tip)
            Me.dtpTo.Focus()
            Return False
        End If

        '检查数据类型是否选择
        If Not chkHistory.Checked AndAlso Not chkAlarm.Checked Then
            tip = "请选择要清除历史数据的类型。"
            msg.ShowWarning(tip)
            Me.chkHistory.Focus()
            Return False
        End If

        '高级用户权限允许删除一个月内数据
        If gp.IsInRole(RoleClass.GetRolename(RoleType.HighLevel)) Then
        Else
            '检查历史数据时间范围1个月前
            If Me.chkHistory.Checked AndAlso Me.dtpTo.Value > DateTime.Now.AddMonths(-1) Then
                tip = "不能删除一个月内的历史数据。"
                msg.ShowWarning(tip)
                Me.dtpTo.Focus()
                Return False
            End If

        End If



        '20100519李吉鹏增加限制删除数据量
        If Me.dtpTo.Value > Me.dtpFrom.Value.AddMonths(12) Then
            tip = "清除数据量不能超过一年！"
            msg.ShowWarning(tip)
            Me.dtpTo.Focus()
            Return False
        End If



        Return True

    End Function

    Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        e.Result = DoClear()
    End Sub

    Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted

        lblState.Visible = False

        If e.Result > 0 Then
            msg.Show("数据清理完成。")
        Else
            msg.Show("清理失败或指定时间范围没有数据,请重新设置时间范围！")
        End If

        btnClear.Enabled = True
        Panel1.Enabled = True

    End Sub

    Private Sub DBClearForm_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        e.Cancel = False
        If Not btnClear.Enabled Then
            msg.Show("正在清理数据，无法关闭窗口。")
            e.Cancel = True
        End If
    End Sub
End Class